package pl.edu.agh.ros.node.manager;

import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

import pl.edu.agh.ros.node.conf.XMPPConfiguration;

public final class XMPPManager {

	private Connection connection;

	public Connection connectAndLogin(XMPPConfiguration xmppConfiguration) throws XMPPException {
		return connectAndLogin(xmppConfiguration.getXMPPServerAddress(), xmppConfiguration.getXMPPServerPort(),
				xmppConfiguration.getXMPPUsername(), xmppConfiguration.getXMPPPassword());
	}

	public Connection connectAndLogin(String server, int port, String user, String password) throws XMPPException {
		connect(server, port);
		login(user, password);
		return connection;
	}

	public void disconnect() {
		connection.disconnect();
	}

	public void sendMessage(Message message, String subscriber) {
		try {
			message.setTo(subscriber);
			connection.sendPacket(message);
		} catch (Exception e) {
			//TODO proper logging
		}
	}

	public Connection getConnection() {
		return connection;
	}

	private void connect(String server, int port) throws XMPPException {
		ConnectionConfiguration config = new ConnectionConfiguration(server, port);
		connection = new XMPPConnection(config);
		connection.connect();
	}

	private void login(String user, String password) throws XMPPException {
		connection.login(user, password, String.valueOf(System.currentTimeMillis()));
	}

}
